package com.zx.zxapibackend.controller;

import co.elastic.clients.ApiClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zx.zxapibackend.model.domain.Auth;
import com.zx.zxapibackend.model.domain.User;
import com.zx.zxapibackend.model.dto.interfaceInfo.InterfaceInfoInvokeRequest;
import com.zx.zxapibackend.model.enums.InterfaceInfoEnum;
import com.zx.zxapibackend.service.AuthService;
import com.zx.zxapibackend.service.InterfaceInfoService;
import com.zx.zxapiclientsdk.client.ZxAPIClient;
import com.zx.zxapiclientsdk.model.Api;
import com.zx.zxapicommon.common.BaseResponse;
import com.zx.zxapicommon.exception.BusinessException;
import com.zx.zxapicommon.model.entity.InterfaceInfo;
import com.zx.zxapicommon.model.enums.ErrorCode;
import com.zx.zxapicommon.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 张旭
 * @version 1.0
 */
@RestController
public class InterfaceClientController {
    @Autowired
    private AuthService authService;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    /**
     * 接口在线调用
     *
     * @param userRequestParams
     * @param request
     * @return
     */
    @PostMapping("/apiclient")
    public BaseResponse<Object> apiClient(@RequestBody InterfaceInfoInvokeRequest userRequestParams, HttpServletRequest request) {
        if (userRequestParams == null || userRequestParams.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = userRequestParams.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (oldInterfaceInfo.getStatus() != InterfaceInfoEnum.ONLINE.getValue()) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口关闭");
        }

        //获取当前登录用户
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User currentUser = (User) principal;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        String params = userRequestParams.getUserRequestParams();
        String method = userRequestParams.getMethod();
        String url = userRequestParams.getUrl();
        if (method == null || url == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请求参数错误");
        }
        Api api = new Api();
        api.setInterfaceId(String.valueOf(id));
        api.setId(currentUser.getId());
        api.setUserAccount(currentUser.getUserAccount());
        api.setBody(params);
        api.setUrl(url);
        api.setMethod(method);

        Auth auth = authService.getOne(new QueryWrapper<Auth>()
                .eq("userid", currentUser.getId())
                .ne("status", 1));

        if (auth == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "API密钥不存在 或 API密钥已经被关闭");
        }

        ZxAPIClient apiClient = new ZxAPIClient(Integer.valueOf(auth.getAppid()), auth.getAccessKey(), auth.getSecretKey());
        String result = apiClient.getResult(api);

        if (result.contains("Error request")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "调用错误，请检查调用次数！");
        }
        if (result.contains("500")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "调用错误,请检查请求参数!");
        }

        return ResultUtils.success(result);
    }
}
